// Example two processes comunicating via shared memory: 
// shm_server.c, shm_client.c
// http://www.cs.cf.ac.uk/Dave/C/node27.html

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>

#define SHMSZ 27 

void main(int argc, char* argv[]){
	char c;
	int shmid;
	key_t key;
    char *shm, *s;
	 
     // We'll name our shared memory segment "5678".
    key = 5678;
	// or use file as key: 
	// if ((key = ftok("hello.txt", 'R')) == -1){xxxx} /*Here the file must exist */ 
    
    // create the shared segment
    if( (shmid=shmget(key,SHMSZ,0666|IPC_CREAT)) == -1){
    	perror("shmget error");
    	exit(1);
    }

    // attach the segment to our data space
    shm = shmat(shmid,NULL,0);
    if(shm == (char *)(-1)){
		perror("shmat");
		exit(1);
    }

    // now put some things into mem, for other process to read

    s = shm;
    for( c='a'; c<='z';c++){
    	*s++ = c;
    }
    *s = '\0';

	/*
     * Finally, we wait until the other process 
     * changes the first character of our memory
     * to '*', indicating that it has read what 
     * we put there.
     */
    while (*shm != '*')
        sleep(1);
    
    s=shm;
    printf("other process has change the memory, %s\n",s);
    sleep(20);
    exit(0);
}